package netty.discard;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Instruction：丢弃信息服务器
 * Author：@author MaLi
 */
public class DiscardServer {
    private int port;

    public DiscardServer(int port) {
        this.port = port;
    }

    public void startServer() {

        //创建一个组装器
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        //创建两个事件轮询组: 其中的每一个线程 - EventLoop就是一个Reactor或者SunReactor
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        serverBootstrap.group(bossGroup, workerGroup);

        //创建通道类型: 封装的Channel
        NioServerSocketChannel socketChannel = new NioServerSocketChannel();

        //配置通道参数
        serverBootstrap.channel(socketChannel.getClass());
        serverBootstrap.localAddress(port);
        serverBootstrap.option(ChannelOption.SO_KEEPALIVE, true);

        //创建pipline: 封装的Handler
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new NettyDiscardHandler());
            }
        });

        //绑定服务器端口 Create a new Channel and bind it.
        try {
            ChannelFuture channelFuture = serverBootstrap.bind().sync();//这里为什么创建一个Channel, 并绑定到服务器
            //关闭通道(为什么要关闭通道, 被关闭的是哪个通道 - ServerSocketChannel父通道, 父通道用于轮询新连接事件)
            // Returns the ChannelFuture which will be notified when this channel is closed. - 如果channel被关闭才会调用该回调
            // This method always returns the same future instance.
            // channel什么时候被关闭? --> 应用停止的时候
            channelFuture.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            //关闭两个事件轮询组
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        DiscardServer server = new DiscardServer(8888);
        server.startServer();
    }
}
